package com.ruicar.afs.cloud.batch.dayend.handle.run;

import com.alibaba.fastjson.JSONObject;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.modules.contract.enums.VoucherSendStatus;
import com.ruicar.afs.cloud.common.vo.AccountVoucherInfoVo;
import com.ruicar.afs.cloud.common.voucher.processor.AbsBaseProcessor;
import com.ruicar.afs.cloud.common.voucher.processor.IRequest;
import com.ruicar.afs.cloud.common.voucher.processor.enums.VoucherMsgType;
import com.ruicar.afs.cloud.common.voucher.processor.impl.VoucherResponse;
import com.ruicar.afs.cloud.voucher.dto.VoucherSendInfoDto;
import com.ruicar.afs.cloud.voucher.feign.VoucherApiFeign;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
@Slf4j
@AllArgsConstructor
public class VoucherBathSendProcessor extends AbsBaseProcessor<VoucherBathRequest, VoucherResponse> {
    private final VoucherApiFeign voucherApiFeign;

    @Override
    public VoucherMsgType msgType() {
        return VoucherMsgType.CONFIDENTIAL_INFORMATION;
    }
    @Override
    public  List<AccountVoucherInfoVo> process(VoucherBathRequest request) {
        String errMsg=null;
        VoucherSendStatus status;
        //发送凭证信息
        VoucherResponse response = this.callServer(request);
        if(CommonConstants.SUCCESS.equals(response.getCode())){
            errMsg="";
            status=VoucherSendStatus.SEND_SUCCESS;
        }else{
            errMsg=response.getMsg();
            status=VoucherSendStatus.SEND_FAIL;
        }
        //移除重复list
        List<AccountVoucherInfoVo> list =removeDuplicateWithOrder(request.getVos(),errMsg,status);
        return list ;
    }
    @Override
    public IRequest getRequestParams(VoucherBathRequest request) {
        return request.get();
    }
    @Override
    public VoucherResponse processRsp(JSONObject jsonObject) {
        VoucherResponse response = JSONObject.toJavaObject(jsonObject,VoucherResponse.class);
        return  VoucherResponse.convertFrom(response);
    }

    @Override
    public JSONObject send(IRequest iRequest) {
        return voucherApiFeign.send((List<VoucherSendInfoDto>) iRequest.getData());
    }

    public List<AccountVoucherInfoVo>  removeDuplicateWithOrder(List list,String errMsg, VoucherSendStatus status) {
        Set set = new HashSet();
        List newList = new ArrayList();
        for (Iterator<AccountVoucherInfoVo> iter = list.iterator(); iter.hasNext();) {
            AccountVoucherInfoVo accountVoucherInfoVo = iter.next();
            if (set.add(accountVoucherInfoVo.getId())) {
                accountVoucherInfoVo.setStatus(status);
                accountVoucherInfoVo.setErrMsg(errMsg);
                newList.add(accountVoucherInfoVo);
            }
        }
        list.clear();
        list.addAll(newList);
        return list;
    }

}
